import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebActivity extends StatefulWidget {
  @override
  _WebActivityState createState() => _WebActivityState();
}

class _WebActivityState extends State<WebActivity> {
  WebViewController _controller;
  String title;

  @override
  Widget build(BuildContext context) {
    //https://www.jianshu.com/p/4aabe453eb26
    return Scaffold(
      appBar: AppBar(
        title: Text(title == null ? "webview测试" : title),
      ),
      body: WebView(
        initialUrl: "https://flutterchina.club/",
        //JS执行模式 是否允许JS执行
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (controller) {
          _controller = controller;
        },
        onPageFinished: (url) {
          //执行js方法
          _controller.evaluateJavascript("document.title").then((reslut) {
            title = reslut;
            setState(() {});
          });
        },
        //提供给js的方法（JS通过这个name去post对应的信息给Flutter（API为name.postMessage('xxxxxx')））
        javascriptChannels: <JavascriptChannel>[
          JavascriptChannel(
              name: "object",
              onMessageReceived: (JavascriptMessage message) {
                print("参数： ${message.message}");
              }),
        ].toSet(),
      ),
    );
  }
}
